bad(red1).
bad(red2).
bad(red3).
bad(red4).
bad(red5).
bad(red6).

// whether to go to hospital
go_hospital  :- carrying_victim(3).
//go_hospital :- carrying_victim(N) & N > 0 & pos(_,_,Step) & steps(_,NSteps) & Step+200 > NSteps.
go_hospital :- carrying_victim(N) & N > 0 & hosp_mais_prox(DX,DY) & pos(X,Y,_) & jia.path_length(X,Y,DX,DY,PL) & PL <= 4.
go_hospital :- carrying_victim(N) & N > 0 & pos(X,Y,Step) & hosp_mais_prox(DX,DY) & jia.path_length(X,Y,DX,DY,PL) & steps(_,NSteps) & Step+PL + 50 > NSteps.


hosp_mais_prox(DX,DY) :-
	.findall(h(_,XH,YH),hospital(_,XH,YH),L1) & calc_dist(L1,L2) &  
    .sort(L2,[h(_,DX,DY)|_]). 

calc_dist([],[]).
calc_dist([h(_,X,Y)|T1],[h(D,X,Y)|T2]) :-
   pos(XP,YP,_) & jia.path_length(XP,YP,X,Y,D) & calc_dist(T1,T2).



// find a free random location    
random_pos(X,Y) :-
   pos(AgX,AgY,_) & quad(IX,IY,FX,FY) &
   jia.random(RX,20)  & X = (RX-10)+AgX & X > 0 &
   jia.random(RY,20,5) & Y = (RY-10)+AgY &
   not jia.obstacleB(X,Y,IX,IY,FX,FY) & 
   not hospital(_,X,Y).  


+quad(X,Y,FX,FY)	<- -+back_pos((X+FX)/2,(Y+FY)/2).

	
/* -- Victim found! -- */
// in the positon of the agent
+pos(X,Y,_) 
   : cell(X,Y,victim) &
     carrying_victim(N) & N < 3 // container has space 
  <- do(pick);
     .print("picked victim!").
     //-+back_pos(X,Y). // remembers a place to return 

// in a cell besides
+pos(X,Y,_) 
   : cell(GX,GY,victim) &
     carrying_victim(N) & N < 3 // container has space 
  <- jia.direction(X, Y, GX, GY, D);
     do(D).
  
/* -- has victim, carry it/them to hospital -- */

// when I arrive at hospital
+pos(X,Y,_) 
   : go_hospital & 
     hospital(_,X,Y) 
  <- .print("at hospital");
     do(drop).

// when still not in hospital
+pos(X,Y,_) 
   : go_hospital &
     hosp_mais_prox(DX,DY)
  <- jia.direction(X, Y, DX, DY, D); // uses A* to find a path to the hospital
     //.print("from ",X,"x",Y," to ",DX,"x",DY," -> ",D);
     do(D).

/* -- go to the back pos -- */

// at the back_pos
+pos(X,Y,_) 
   : back_pos(X,Y) | // I am at back pos, find another 
     (back_pos(BX,BY) & jia.direction(X, Y, BX, BY, skip)) // impossible to go to back_pos, find another
  <- !define_new_pos.
  
+pos(X,Y,_) 
   : back_pos(BX,BY) & jia.direction(X, Y, BX, BY, D) // one step towards back_pos
  <- do(D).
     
/* -- random move --   
+pos(_,_,_) 
   <- !define_new_pos.*/
      
+!define_new_pos
   <- ?pos(X,Y,_);
      ?random_pos(NX,NY);
      
     //.print("New point ",NX,",",NY);
      -+back_pos(NX,NY);      
      jia.direction(X, Y, NX, NY, D);
      do(D).
      
+!kqml_received(Sender, _, _, _) : bad(Sender).